﻿using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;

namespace ToolUtil
{
    public class ShowMessageBox
    {
        #region 自动关闭消息框

        // 寻找窗口的API函数
        [DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        // 关闭窗口的API函数
        [DllImport("user32.dll")]
        static extern bool EndDialog(IntPtr hDlg, out IntPtr nResult);

        /// <summary>
        /// 可定时自动关闭的消息框 ,
        /// text-->内容 ,
        /// caption-->标题 ,
        /// buttons-->MessageBoxButtons.XX ,
        /// timeout-->定时
        /// </summary>
        /// <param name="text">消息框的主体内容</param>
        /// <param name="caption">消息框的标题内容</param>
        /// <param name="buttons">消息按钮，MessageBoxButtons.XX</param>
        /// <param name="timeout">自动关闭定时，单位毫秒</param>
        public static void ShowMessageBoxTimeout(string text, string caption,
             MessageBoxButtons buttons, int timeout)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(CloseMessageBox),
               new CloseState(caption, timeout));
            MessageBox.Show(text, caption, buttons);
        }

        // 定义类
        private class CloseState
        {
            private int _Timeout;

            ///<summary>
            /// 单位毫秒 1s = 1000ms
            ///</summary>
            public int Timeout
            {
                get
                {
                    return _Timeout;
                }
            }

            private string _Caption;

            ///<summary>
            /// 提示窗口的标题
            ///</summary>
            public string Caption
            {
                get
                {
                    return _Caption;
                }
            }

            public CloseState(string caption, int timeout)
            {
                _Timeout = timeout;
                _Caption = caption;
            }
        }

        private static void CloseMessageBox(object state)
        {
            CloseState closeState = state as CloseState;

            Thread.Sleep(closeState.Timeout);
            IntPtr dlg = FindWindow(null, closeState.Caption);

            if (dlg != IntPtr.Zero)
            {
                IntPtr result;
                EndDialog(dlg, out result);
            }
        }

        #endregion
    }
}
